import { exec } from 'child_process';
import fs from 'fs';
import lodash from 'lodash';
import { createRequire } from 'module';
import path, { dirname } from 'path';
import prettier from 'prettier';
import { fileURLToPath } from 'url';

function copy(params) {
  exec('pbcopy').stdin.end(params);
}

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const require = createRequire(import.meta.url);
const cwd = process.cwd();
const prettierrc = JSON.parse(
  fs.readFileSync(path.resolve(cwd, '.prettierrc'), 'utf-8'),
);
let projectDir = path.resolve(cwd, 'components/quasar/components');
let toDir = path.resolve(cwd, 'components/teld/basic');
let components = fs.readdirSync(projectDir, { encoding: 'utf-8' });

fs.rmSync(toDir, { recursive: true, force: true });
fs.mkdirSync(toDir);

let importString = ``;
let contentString = `const components = [`;
for (let i = 0; i < components.length; i++) {
  let e = components[i];
  let kebabCaseName = lodash.kebabCase(e);
  let capitalizeName = lodash.capitalize(e);
  let camelCaseName = lodash.camelCase(e);
  let snakeCaseName = lodash.snakeCase(e);
  let startCaseName = lodash.startCase(e);
  let ComponentsCaseName = lodash.upperFirst(camelCaseName);
  let toPathFile = path.resolve(toDir, kebabCaseName);
  let toPath = toPathFile;
  if (fs.statSync(path.resolve(projectDir, e)).isFile()) {
    continue;
  }
  if (fs.existsSync(path.resolve(projectDir, e, 'index.js'))) {
  } else {
    console.log(e);
  }

  if (e === 'spinner') {
    let a = fs
      .readdirSync(path.resolve(projectDir, e))
      .filter(v => /.js$/.test(v) && /^Q/.test(v));

    continue;
  }

  fs.rmSync(toPath, { recursive: true, force: true });
  fs.mkdirSync(toPath);

  fs.copyFileSync(
    path.resolve(__dirname, './template/index.module.scss'),
    path.resolve(toPath, 'index.module.scss'),
  );
  fs.copyFileSync(
    path.resolve(__dirname, './template/index.scss'),
    path.resolve(toPath, 'index.scss'),
  );
  fs.copyFileSync(
    path.resolve(__dirname, './template/index.js'),
    path.resolve(toPath, 'index.js'),
  );

  let t = fs
    .readFileSync(path.resolve(__dirname, './template/Component.jsx'), {
      encoding: 'utf-8',
    })
    .replaceAll('template', e);
  t = await prettier.format(t, { parser: 'typescript' });
  fs.writeFileSync(path.resolve(toPath, 'Component.jsx'), t, {
    encoding: 'utf-8',
  });

  let a = fs
    .readdirSync(path.resolve(projectDir, e))
    .filter(v => /.js$/.test(v));
  let i1 = ``;
  let i2 = ``;
  for (let i_ = 0; i_ < a.length; i_++) {
    const e_ = a[i_];
    // console.log(e, e_);
    let t = fs.readFileSync(path.resolve(projectDir, e, e_), {
      encoding: 'utf-8',
    });
    let t2 = fs.readFileSync(path.resolve(projectDir, e, 'index.js'), {
      encoding: 'utf-8',
    });

    let ss = `export default `;
    let i = t2.indexOf(ss);
    ss = t2
      .substring(i + ss.length)
      .replace(';', '')
      .trim();
    if (t.includes(`name: 'Q`) && !t.includes(`name: '${ss}'`)) {
      let n_ = e_.replace(/^Q/, '').replace('.js', '');
      let s = fs
        .readFileSync(path.resolve(__dirname, './template/Component.jsx'), {
          encoding: 'utf-8',
        })
        .replaceAll('template', e)
        .replaceAll(
          'import Component   ',
          `import {${e_.replace('.js', '')} as Component}`,
        );
      s = await prettier.format(s, { parser: 'typescript' });
      fs.writeFileSync(path.resolve(toPath, n_ + '.jsx'), s, {
        encoding: 'utf-8',
      });
      i1 += `import ${n_} from './${n_}';`;
      i2 += `app.component(${n_}.name, ${n_});`;
      console.log(e, e_);
    }
  }

  if (i1 && i2) {
    let sss = `import Component    from './Component';

export * from './Component';

export default Object.assign(Component, {
  install: (app, options, ssrContext) => {
    app.component(Component.name, Component);
  },
});
`;
    let s = fs.readFileSync(path.resolve(toPath, 'index.js'), {
      encoding: 'utf-8',
    });

    s = s
      .replaceAll(
        `import Component    from './Component';`,
        `import Component    from './Component';` + i1,
      )
      .replaceAll(
        `app.component(Component.name, Component);`,
        `app.component(Component.name, Component);` + i2,
      );
    s = await prettier.format(s, { parser: 'typescript' });
    fs.writeFileSync(path.resolve(toPath, 'index.js'), s, {
      encoding: 'utf-8',
    });
  }

  importString += `import ${ComponentsCaseName} from './basic/${e}';`;
  contentString += `${ComponentsCaseName},`;
  // indexJSX = await prettier.format(indexJSX, { parser: 'typescript' });
}
contentString += `];`;
let t = fs
  .readFileSync(path.resolve(__dirname, './template/entry.js'), {
    encoding: 'utf-8',
  })
  .replaceAll(`import Button from './basic/button';`, importString)
  .replaceAll(`const components = [Button];`, contentString);
t = await prettier.format(t, { parser: 'typescript' });
fs.writeFileSync(path.resolve(cwd, 'components/teld/index.js'), t, {
  encoding: 'utf-8',
});
